package com.cpj.bsyyzx.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpj.bsyyzx.entity.Account;
import com.cpj.bsyyzx.service.IAccountService;
import com.cpj.bsyyzx.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 五个臭皮匠
 * @since 2021-04-27
 */
@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    IAccountService accountService;

    public static final String KEY = "loginUser";

    @RequestMapping("/token")
    CommonResult token(Account account){
        System.out.println(account);
        if (account!=null){
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("username",account.getUsername());
            Account account1=accountService.getOne(wrapper);
            if (account1!=null){
                if (account.getPassword().equals(account1.getPassword())){
                    JWTCreator.Builder builder = JWT.create();
                    String token = builder.withClaim("accId", account1.getAccId())
                            .withClaim("username", account1.getUsername())
                            .sign(Algorithm.HMAC256("loginUser"));
                    return CommonResult.success(token);
                }
            }
        }
        return CommonResult.failed("用户名或者密码错误");
    }

    @RequestMapping("list")
    CommonResult list(Page page,Account account){
        page= accountService.pageList(page,account);
        return  CommonResult.success(page);
    }

    @RequestMapping("delete")
    CommonResult del(Integer id){
        return CommonResult.success(accountService.removeById(id));
    }

    @RequestMapping("getOne")
    CommonResult getOne(Integer id){
        return CommonResult.success(accountService.getById(id));
    }

    @RequestMapping("save")
    CommonResult save(Account account){
        return CommonResult.success(accountService.saveOrUpdate(account));
    }


    @RequestMapping("getUsername")
    CommonResult getUsername(HttpServletRequest request){
        String method = request.getMethod();
        if(method.toLowerCase().equals("option")){
            CommonResult.success(null);
        }
        String token = request.getHeader("token");
        JWTVerifier verifier= JWT.require(Algorithm.HMAC256("loginUser")).build();
        DecodedJWT jwt =verifier.verify(token);
        String username = jwt.getClaim("username").asString();
        return CommonResult.success(username);
    }
}
